/*
 * @Author: your name
 * @Date: 2020-10-13 09:46:25
 * @LastEditTime: 2020-11-06 13:43:27
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nuxt-iview\middleware\i18n.js
 */
import Cookie from 'js-cookie' // 新增

function getcookiesInServer(req) {
  const service_cookie = {}
  req && req.headers.cookie && req.headers.cookie.split(';').forEach(function(val) {
    const parts = val.split('=')
    service_cookie[parts[0].trim()] = (parts[1] || '').trim()
  })
  return service_cookie
}
//获取客户端cookie
function getcookiesInClient(key) {
  return Cookie.get(key) ? Cookie.get(key) : '';
}

export default function({ isHMR, app, store, route, params, error, redirect, req }) {
  let language = '';
  const defaultLocale = app.i18n.fallbackLocale;

  // Get locale from params
  const locale = params.lang || defaultLocale
  if (store.state.content.locales.indexOf(locale) === -1) {
    return error({ message: 'This page could not be found.', statusCode: 404 })
  }
  // Set locale
  //在客户端判读是否需要登陆
  if (process.client) {
    language = getcookiesInClient('language');
  }
  //在服务端
  if (process.server) {
    language = getcookiesInServer(req)
  }
  // If middleware is called from hot module replacement, ignore it
  if (isHMR) return
  // Get locale from params
  store.commit('content/SET_LANGUAGE', language)
  app.i18n.locale = store.state.content.locale
  // If route is /<defaultLocale>/... -> redirect to /...
  if (locale === defaultLocale && route.fullPath.indexOf('/' + defaultLocale) === 0) {
    const toReplace = '^/' + defaultLocale + (route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '')
    const re = new RegExp(toReplace)
    return redirect(
      route.fullPath.replace(re, '/')
    )
  }
}
